var chatRemote = require('../remote/chatRemote');

module.exports = function (app) {
	return new Handler(app);
};

var Handler = function (app) {
	this.app = app;
};

var handler = Handler.prototype;

/**
 * Send messages to users
 *
 * @param {Object} msg message from client
 * @param {Object} session
 * @param  {Function} next next stemp callback
 *
 */
handler.push = function (msg, session, next) {
	console.log("chatHandler.push: msg is %s.", msg);
	var rid = session.get('rid');
	var uid = session.uid;
	var channelService = this.app.get('channelService');
	var param = {
		from: uid,
		to: msg.to,
		content: msg.content,
	};
	channel = channelService.getChannel(rid, false);

	if (msg.to == "*") {
		// 推送至所有玩家
		channel.pushMessage('onChat', param);
	}
	else {
		// 推送至具体的玩家
		var tuid = msg.to;
		var tsid = channel.getMember(tuid)["sid"];
		channelService.pushMessageByUids('onChat', param, [{
			uid: tuid,
			sid: tsid
		}]);
	}
	next(null, {
		route: msg.route
	});
};

handler.pull = function (msg, session, next) {
	var rid = session.get("rid");
	var uid = session.uid;
	console.log("handler.pull: rid is ", rid);
	console.log("handler.pull: uid is ", uid);
	var channelService = this.app.get("channelService");
	var channel = channelService.getChannel(rid, false);
	var uids = channel.getMembers();
	next(null, { rid: rid, uids: uids });
};

handler.login = function (msg, session, next) {

};

handler.logout = function (msg, session, next) {

}